package com.chx.three.mama.fragments;


import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.chx.three.mama.R;
import com.chx.three.mama.activities.RingBBSActivity;
import com.chx.three.mama.adapter.DragListAdapter;
import com.chx.three.mama.model.RingItem;
import com.chx.three.mama.utils.Constants;
import com.chx.three.mama.utils.SPHelper;
import com.chx.three.mama.view.CheckNetImageView;
import com.chx.three.mama.view.DragListView;
import com.chx.three.mama.view.Topbar;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 圈子的fragment
 */
public class RingFragment extends Fragment implements Topbar.onTopbarClickListener, AdapterView.OnItemClickListener {
    Topbar topbar;
    private ArrayList<RingItem> ringItems;
    private boolean isSorting;
    //开头动画布局
    CheckNetImageView checkNetView;
    //数据列表
    /**
     * 请求队列，用于发送网络请求
     */
    private RequestQueue requestQueue;

    //数据适配器
    private DragListAdapter adapter = null;

    public RingFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_ring, container, false);
        topbar = (Topbar) inflate.findViewById(R.id.topbar);
        topbar.setOnTopbarClickListener(this);
        checkNetView = (CheckNetImageView) inflate.findViewById(R.id.ring_check_net);
        //初始化样本数据
        initData();


        DragListView dragListView = (DragListView)inflate.findViewById(R.id.other_drag_list);
        dragListView.setOnItemClickListener(this);
        ringItems=new ArrayList<>();
        adapter = new DragListAdapter(getActivity(), ringItems);
        dragListView.setAdapter(adapter);
        return inflate;
    }

    public void initData()   {
        requestQueue = Volley.newRequestQueue(getActivity());
        String path= Constants.URL.RING_LIST+"&"+SPHelper.SP_KEY_0_USER_ID+"="+ SPHelper.getUserId();
        final JsonObjectRequest request = new JsonObjectRequest(path,
                new JSONObject(),
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject object) {
                        JSONArray jsonArray = object.optJSONArray("data");
                        List<RingItem> items = JSON.parseArray(jsonArray.toString(), RingItem.class);
                        ringItems.addAll(items);
                        sortData();
                        adapter.notifyDataSetChanged();
                        checkNetView.onResponse();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        checkNetView.onError();
                    }
                });
        request.setTag("load");
        requestQueue.add(request);
        checkNetView.setOnDoubleClickListener(new CheckNetImageView.OnDoubleClickListener() {
            @Override
            public void onDoubleClick() {
                requestQueue.cancelAll("load");
                requestQueue.add(request);
            }
        });
    }


    @Override
    public void onLeftButtonClick() {
    }

    @Override
    public void onRightButtonClick() {
        if(isSorting){
            topbar.setRightTextTitle("排序");
            for (RingItem ringItem : ringItems) {
                ringItem.setSorting(false);
            }
            isSorting=false;
        }else{
            topbar.setRightTextTitle("完成");
            for (RingItem ringItem : ringItems) {
                ringItem.setSorting(true);
            }
            isSorting=true;
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onSearchButtonClick() {

    }
    private ArrayList<Integer> sort;

    /**
     * 排序数据
     */
    public void sortData(){
        sort=new ArrayList<>();
        String listSort = SPHelper.getRingListSort();
        int size = ringItems.size();
        String[] split = listSort.split(",");
        for (int i = 0; i < split.length; i++) {
            if(!TextUtils.isEmpty(split[i])){
                sort.add(i, Integer.parseInt(split[i]));
            }
        }
        if(sort.size()<size){
            for (int i = sort.size(); i < size; i++) {
                sort.add(i);
            }
        }
        if(sort.size()>size){
            for (int i = size-1; i >= sort.size(); i--) {
                sort.remove(i);
            }
        }
        setSort();
        List<RingItem> copyList=new ArrayList<>();
        for (int i = 0; i < size; i++) {
            copyList.add(ringItems.get(sort.get(i)));
        }
        ringItems.clear();
        ringItems.addAll(copyList);
    }
    private void setSort() {
        StringBuilder sb=new StringBuilder();
        for (int i = 0; i < sort.size(); i++) {
            sb.append(sort.get(i));
            sb.append(",");
        }
        SPHelper.setRingListSort(sb.toString());
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        RingItem ringItem = ringItems.get(position);
        Intent intent=new Intent(getActivity(), RingBBSActivity.class);
        intent.putExtra(Constants.BundleKey.KEY_RING_TO_BBS,ringItem);
        startActivity(intent);
    }
}
